<?
class turnController extends Controller_Action
{
    public function preDispatch() 
    {
        $user = $this->getVkUser();
        if (!$user) {
            $this->_redirect('/auth');
        }

        parent::preDispatch();
    }
    
    public function indexAction()
    {
        
    }
    
    /**
     * Создание новой очереди для сообщества
     */
    public function createAction()
    {
        if ($this->getRequest()->isPost()) {
            if (!$this->_getParam('name')) {
                throw new Zend_Controller_Action_Exception('Не указано название очереди');
            }
            
            $turn = TurnPeer::getInstance()->findByName($this->_getParam('name'));
            
            if ($turn->count()) {
                throw new Zend_Controller_Action_Exception('Очередь с именем "' . $this->_getParam('name') . '" уже создана');
            }
            
            if (!$this->_getParam('group')) {
                throw new Zend_Controller_Action_Exception('Не указана группа');
            }
            
            $group = GroupsPeer::getInstance()->findByName($this->_getParam('group'));
            
            if (!$group->count()) {
                throw new Zend_Controller_Action_Exception('Группа ' . $this->_getParam('group') . ' не найдена');
            }
            
            if (!$this->_getParam('time')) {
                throw new Zend_Controller_Action_Exception('Не указано время');
            }
            
            $turn = TurnPeer::getInstance();
            $turn->insert(
                array(
                    'id' => '',
                    'name' => $this->_getParam('name'),
                    'group_id' => $group[0]->id,
                    'created_at' => date('Y-m-d H:i:s'),
                    'modified_at' => date('Y-m-d H:i:s')
                )
            );
            
            $turnId = TurnPeer::getInstance()->getAdapter()->lastInsertId();
            
            $time = explode("\n", $this->_getParam('time'));
            foreach($time as $t) {
                if (!preg_match('/[0-9]{1,2}:[0-9]{2}/', $t)) {
                    throw new Zend_Controller_Action_Exception('Не верный формат времени ' . $t);
                }
                $timeRow = TurnTimePeer::getInstance()->createRow();
                $timeRow->setTurnId($turnId);
                $timeRow->setTime($t);
                $timeRow->setCreatedAt(date('Y-m-d H:i:s'));
                $timeRow->setModifiedAt(date('Y-m-d H:i:s'));
                $timeRow->save();
            }
            $this->view->message = 'Очередь <b>' . $this->_getParam('name') . '</b> успешно создана';
        }
    }
    
    /**
     * AJAX действие - Возвращает список очередей
     */
    public function getTurnsAction()
    {
        $this->_ajaxOnly();
        if (!$this->_getParam('group')) {
            throw new Zend_Controller_Action_Exception('Не указана группа');
        }
        
        $group = GroupsPeer::getInstance()->findByVkId($this->_getParam('group'))->current();
        if (!$group) {
            throw new Zend_Controller_Action_Exception('Группа не найдена');
        }
        
        $turns = TurnPeer::getInstance()->findByGroupId($group->id)->current();
        
        // извлекать только одну очередь
        $this->view->tid = $turns->getId();
        $select = TurnPostPeer::getInstance()->select();
		$select->where('turn_id = ?', $turns->getId());
        $select->where('is_posted = ?', 0);
        $select->order('post_date ASC');
        $select->order('post_time ASC');
        $this->view->posts = $turns->getTurnPostRowsetByTurnId($select);        
    }
    
    /**
     * Редактирование очереди 
     */
    public function editAction(){
        if ($this->getRequest()->isPost()) {
            if (!$this->_getParam('tid')) {
                throw new Zend_Controller_Action_Exception('Не указана очередь');
            }
            
            if (!$this->_getParam('name')) {
                throw new Zend_Controller_Action_Exception('Не указано название очереди');
            }
            
            $turn = TurnPeer::getInstance()->findById($this->_getParam('tid'))->current();
            
            if (!$turn) {
                throw new Zend_Controller_Action_Exception('Очередь не найдена');
            }
            
            if (!$this->_getParam('group')) {
                throw new Zend_Controller_Action_Exception('Не указана группа');
            }
            
            $group = GroupsPeer::getInstance()->findByName($this->_getParam('group'));
            
            if (!$group->count()) {
                throw new Zend_Controller_Action_Exception('Группа ' . $this->_getParam('group') . ' не найдена');
            }
            
            if (!$this->_getParam('time')) {
                throw new Zend_Controller_Action_Exception('Не указано время');
            }
            
            $turnUpdate = TurnPeer::getInstance();
            $turnUpdate->update(array(
                'name' => $this->_getParam('name'),
                'group_id' => $group[0]->id,
                'modified_at' => date('Y-m-d H:i:s')
            ), 'id = ' . $this->_getParam('tid'));
            
            $turnTime = TurnTimePeer::getInstance()->findByTurnId($turn->id);
            
            if ($turnTime->count()) {
                TurnTimePeer::getInstance()->delete('turn_id = ' . $this->_getParam('tid'));
            }
            
            $time = explode("\n", trim($this->_getParam('time'), "\n"));
            foreach($time as $t) {
                if (!preg_match('/[0-9]{1,2}:[0-9]{2}/', $t)) {
                    throw new Zend_Controller_Action_Exception('Не верный формат времени ' . $t);
                }
                $timeRow = TurnTimePeer::getInstance()->createRow();
                $timeRow->setTurnId($turn->id);
                $timeRow->setTime($t);
                $timeRow->setCreatedAt(date('Y-m-d H:i:s'));
                $timeRow->setModifiedAt(date('Y-m-d H:i:s'));
                $timeRow->save();
            }
            $this->view->message = 'Очередь <b>' . $this->_getParam('name') . '</b> успешно сохранена';
        }
        
        if (!$this->_getParam('id')) {
            throw new Zend_Controller_Action_Exception('Не указана очередь');
        }
        
        $turn = TurnPeer::getInstance()->findById($this->_getParam('id'))->current();
        
        if (!$turn) {
            throw new Zend_Controller_Action_Exception('Очередь не найдена');
        }
        
        $this->view->tid = $turn->id;
        $this->view->turn_name = $turn->name;
        $this->view->group = $turn->group_id;
        $this->view->times = $turn->getTurnTimeRowsetByTurnId();
		
		$select = TurnPostPeer::getInstance()->select();
		$select->where('turn_id = ?', $turn->getId());
        $select->where('is_posted = ?', 0);
        $select->order('post_date ASC');
        $select->order('post_time ASC');
        $this->view->posts = $turn->getTurnPostRowsetByTurnId($select); 
    }
	
	public function editPostAction()
	{
		$this->_ajaxOnly();
		if (!$this->_getParam('post_id') && !$this->_getParam('tid') && !$this>_getParam('date') && !$this->_getParam('time')) {
			throw new Zend_Controller_Action_Exception('Не указаны параметры');
		}
		
		if (!preg_match('/([0-9]{4})\-([0-9]{2})\-([0-9]{2})/', $this->_getParam('date'))) {
			throw new Zend_Controller_Action_Exception('Не верный формат даты');
		}
		
		if (!preg_match('/^([0-9]{2})\:([0-9]{2})$/', $this->_getParam('time'))) {
			throw new Zend_Controller_Action_Exception('Не верный формат времени');
		}
		
		$select = TurnPostPeer::getInstance()->select()
				->where('id = ?', $this->_getParam('post_id'))
				->where('turn_id = ?', $this->_getParam('tid'));
		
		$row = TurnPostPeer::getInstance()->fetchRow($select);
		if (!$row) {
			throw new Zend_Controller_Action_Exception('Пост с указанным ID не найден');
		}
		
		$row->post_date = $this->_getParam('date');
		$row->post_time = $this->_getParam('time');
		$row->text = $this->_getParam('text');
		$row->save();
		
		$this->_setAjaxResponse('ok');
	}
	
	public function deletePostAction()
	{
		$this->_ajaxOnly();
		if (!$this->_getParam('post_id') && !$this->_getParam('tid')) {
			throw new Zend_Controller_Action_Exception('Не указаны параметры');
		}
		
		TurnPostPeer::getInstance()->delete(array(
			'id = ' . $this->_getParam('post_id'),
			'turn_id = ' . $this->_getParam('tid')
		));
		
		$this->_setAjaxResponse('ok');
	}
    
}